<?php
if (!defined('ABSPATH')) {
    exit;
}

class NX_Custom_Sort_Frontend {
    public function __construct() {
        add_shortcode('nx_custom_sort_list', [$this, 'render_sorted_list']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('pre_get_posts', [$this, 'apply_category_sort']);
    }

    public function enqueue_scripts() {
        wp_enqueue_script('nx-custom-sort-frontend', NX_CUSTOM_SORT_PLUGIN_URL . 'assets/js/frontend.js', ['jquery'], '1.0.0', true);
        wp_enqueue_style('nx-custom-sort-frontend', NX_CUSTOM_SORT_PLUGIN_URL . 'assets/css/frontend.css', [], '1.0.0');
        wp_localize_script('nx-custom-sort-frontend', 'nxCustomSort', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('nx-custom-sort-nonce')
        ]);
    }

    public function render_sorted_list($atts) {
        $atts = shortcode_atts(['rule_id' => ''], $atts);
        $rule = NX_Custom_Sort_DB::get_rule($atts['rule_id']);
        if (!$rule) {
            return '<p>' . __('Invalid rule ID', 'nx-custom-sort') . '</p>';
        }

        $args = [
            'post_type' => $rule->post_type,
            'post__in' => $rule->sort_order,
            'orderby' => 'post__in',
            'posts_per_page' => -1
        ];
        if ($rule->category_slug) {
            $args['tax_query'] = [
                [
                    'taxonomy' => $rule->post_type === 'product' ? 'product_cat' : 'category',
                    'field' => 'slug',
                    'terms' => $rule->category_slug
                ]
            ];
        }
        if ($rule->slugs) {
            $args['post_name__in'] = $rule->slugs;
        }

        $query = new WP_Query($args);
        ob_start();
        include NX_CUSTOM_SORT_PLUGIN_DIR . 'templates/sorted-list.php';
        return ob_get_clean();
    }

    public function apply_category_sort($query) {
        if (is_admin() || !$query->is_main_query()) {
            return;
        }
        if (is_tax('product_cat') || is_category()) {
            $term = get_queried_object();
            global $wpdb;
            $rule = $wpdb->get_row($wpdb->prepare(
                "SELECT sort_order FROM {$wpdb->prefix}nx_custom_sort_rules WHERE category_slug = %s",
                $term->slug
            ));
            if ($rule && $rule->sort_order) {
                $query->set('post__in', maybe_unserialize($rule->sort_order));
                $query->set('orderby', 'post__in');
            }
        }
    }
}

?>
